package com.sg.untils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtils {

	// 1 可以把几个字符串定义成常量
	private static final String USER = "root";
	private static final String UPWD = "root";
	private static final String URL = "jdbc:mysql://localhost:3306/ljh?characterEncoding=utf-8";
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	// 2 注册驱动
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// 3 得到数据库连接
	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(URL, USER, UPWD);
	}

	// 4 关闭连接 执行 的打开资源
	public static void close(Connection connection, Statement statement) {
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	// 5 关闭所有的打开资源
	public static void close(Connection connection, Statement statement, ResultSet rs) {
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}
